#!/bin/bash

VERSION=0.27.0
PREFIX=/usr/local/frp

Install(){
    if [ ! -d "$PREFIX" ]; then
        which wget || yum install -y wget
        # wget -c https://github.com/fatedier/frp/releases/download/v${VERSION}/frp_${VERSION}_linux_amd64.tar.gz
        wget -c https://gitee.com/yx571304/my_oschina/raw/master/frp/frp_${VERSION}_linux_amd64.tar.gz
        tar xf frp_${VERSION}_linux_amd64.tar.gz
        mv frp_${VERSION}_linux_amd64 $PREFIX
        mkdir -p /etc/frp
    fi
}

ConfigFrps(){
    FRPS_CNF=/etc/frp/frps.ini
    ln -sf $PREFIX/frps /usr/bin/frps
    ln -sf $PREFIX/frps.ini $FRPS_CNF
    echo '[common]' > $FRPS_CNF
    echo 'bind_addr = 0.0.0.0' >> $FRPS_CNF
    echo 'bind_port = 7000' >> $FRPS_CNF
    echo 'bind_udp_port = 7001' >> $FRPS_CNF
    echo 'kcp_bind_port = 7000' >> $FRPS_CNF
    echo 'vhost_http_port = 80' >> $FRPS_CNF
    echo 'vhost_https_port = 443' >> $FRPS_CNF
    echo 'dashboard_port = 7500' >> $FRPS_CNF
    echo 'dashboard_user = admin' >> $FRPS_CNF
    echo 'dashboard_pwd = admin' >> $FRPS_CNF
    echo 'log_max_days = 7' >> $FRPS_CNF
    echo 'max_ports_per_client = 10000' >> $FRPS_CNF
    echo 'token = GMSIPr0dbnnFwOKRV6w8' >> $FRPS_CNF
    echo 'allow_ports = 1-65535' >> $FRPS_CNF
    echo 'max_pool_count = 10000' >> $FRPS_CNF
    echo 'log_file = frps.log' >> $FRPS_CNF
    echo 'log_level = info' >> $FRPS_CNF

    cp $PREFIX/systemd/frps.service /usr/lib/systemd/system/frps.service
    sed -i '/User=/d' /usr/lib/systemd/system/frps.service

    systemctl daemon-reload
    systemctl start frps
    systemctl status frps
    systemctl enable frps    
}

ConfigFrpc(){
    FRPC_CNF=/etc/frp/frpc.ini
  
    ln -sf $PREFIX/frpc /usr/bin/frpc
    ln -sf $PREFIX/frpc.ini $FRPC_CNF
    echo '[common]' > $FRPC_CNF
    echo 'admin_addr = 0.0.0.0' >> $FRPC_CNF
    echo 'server_addr = 0.0.0.0' >> $FRPC_CNF
    echo 'server_port = 7000' >> $FRPC_CNF
    echo 'admin_port = 7400' >> $FRPC_CNF
    echo 'admin_user = admin' >> $FRPC_CNF
    echo 'admin_pwd = admin' >> $FRPC_CNF
    echo 'token = GMSIPr0dbnnFwOKRV6w8' >> $FRPC_CNF
    echo  >> $FRPC_CNF
    echo '[ssh]' >> $FRPC_CNF
    echo 'type = tcp' >> $FRPC_CNF
    echo 'local_ip = 127.0.0.1' >> $FRPC_CNF
    echo 'local_port = 22' >> $FRPC_CNF
    echo 'remote_port = 6000' >> $FRPC_CNF

    cp $PREFIX/systemd/frpc.service /usr/lib/systemd/system/frpc.service
    sed -i '/User=/d' /usr/lib/systemd/system/frpc.service

    systemctl daemon-reload
    systemctl start frpc
    systemctl status frpc
    systemctl enable frpc
}

case "$1" in
    frps)
      Install
      ConfigFrps
      ;;
    frpc)
      Install
      ConfigFrpc
      ;;
    uninstall)
      systemctl stop frpc
      systemctl stop frps
      systemctl disable frpc
      systemctl disable frps
      rm -rf $PREFIX
      ;;
    *)
      echo "Usage: Install frps"
      echo -e "\t $0 frps"
      echo ""
      echo "Usage: Install frpc"
      echo -e "\t $0 frpc"
esac
